<!DOCTYPE html>
<html lang="zh-Hans">
<head>

    <!--[if lt IE 9]>
        <style>body {display: none; background: none !important} </style>
        <meta http-equiv="Refresh" Content="0; url=//outdatedbrowser.com/" />
    <![endif]-->

<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<meta name="format-detection" content="telephone=no" />
<meta name="author" content="HatBoy" />



<meta name="description" content="前面几章介绍了Cython如何和Python一起工作，侧重于基础数据类型和函数，Cython也能在Python类上面做一样好，本章我们将继续学习。">
<meta name="keywords" content="Python,Cython">
<meta property="og:type" content="article">
<meta property="og:title" content="第五章 Cython和扩展类型">
<meta property="og:url" content="http://hatboy.gitee.io/2017/08/10/第五章-Cython和扩展类型/index.html">
<meta property="og:site_name" content="HatBoy的个人主页">
<meta property="og:description" content="前面几章介绍了Cython如何和Python一起工作，侧重于基础数据类型和函数，Cython也能在Python类上面做一样好，本章我们将继续学习。">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://hatboy.gitee.io/2017/08/10/第五章-Cython和扩展类型/1.png">
<meta property="og:updated_time" content="2017-12-21T10:14:31.798Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="第五章 Cython和扩展类型">
<meta name="twitter:description" content="前面几章介绍了Cython如何和Python一起工作，侧重于基础数据类型和函数，Cython也能在Python类上面做一样好，本章我们将继续学习。">
<meta name="twitter:image" content="http://hatboy.gitee.io/2017/08/10/第五章-Cython和扩展类型/1.png">

<link rel="apple-touch-icon" href= "/apple-touch-icon.png">


    <link rel="alternate" href="/atom.xml" title="HatBoy的个人主页" type="application/atom+xml">



    <link rel="shortcut icon" href="/img/favicon.ico">



    <link href="//cdn.bootcss.com/animate.css/3.5.1/animate.min.css" rel="stylesheet">



    <link href="//cdn.bootcss.com/fancybox/2.1.5/jquery.fancybox.min.css" rel="stylesheet">



    <script src="//cdn.bootcss.com/pace/1.0.2/pace.min.js"></script>
    <link href="//cdn.bootcss.com/pace/1.0.2/themes/blue/pace-theme-minimal.css" rel="stylesheet">


<link rel="stylesheet" href="/css/style.css">



<link href="//cdn.bootcss.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet">


<title>第五章 Cython和扩展类型 | HatBoy的个人主页</title>

<script src="//cdn.bootcss.com/jquery/2.2.4/jquery.min.js"></script>
<script src="//cdn.bootcss.com/clipboard.js/1.5.10/clipboard.min.js"></script>

<script>
    var yiliaConfig = {
        fancybox: true,
        animate: true,
        isHome: false,
        isPost: true,
        isArchive: false,
        isTag: false,
        isCategory: false,
        fancybox_js: "//cdn.bootcss.com/fancybox/2.1.5/jquery.fancybox.min.js",
        scrollreveal: "//cdn.bootcss.com/scrollReveal.js/3.1.4/scrollreveal.min.js",
        search: true
    }
</script>


    <script>
        yiliaConfig.jquery_ui = [true, "//cdn.bootcss.com/jqueryui/1.10.4/jquery-ui.min.js", "//cdn.bootcss.com/jqueryui/1.10.4/css/jquery-ui.min.css"];
    </script>



    <script> yiliaConfig.rootUrl = "\/";</script>





    <script>
        var _hmt = _hmt || [];
        (function() {
            var hm = document.createElement("script");
            hm.src = "//hm.baidu.com/hm.js?04d04bb57e5c5eaf49059aa602440263";
            var s = document.getElementsByTagName("script")[0]; 
            s.parentNode.insertBefore(hm, s);
        })();
    </script>


</head>
<body>
  <div id="container">
    <div class="left-col">
    <div class="overlay"></div>
<div class="intrude-less">
    <header id="header" class="inner">
        <a href="/" class="profilepic">
            <img src="/img/avatar.jpg" class="animated zoomIn">
        </a>
        <hgroup>
          <h1 class="header-author"><a href="/">HatBoy</a></h1>
        </hgroup>

        

        
            <form id="search-form">
            <input type="text" id="local-search-input" name="q" placeholder="search..." class="search form-control" autocomplete="off" autocorrect="off" searchonload="true" />
            <i class="fa fa-times" onclick="resetSearch()"></i>
            </form>
            <div id="local-search-result"></div>
            <p class='no-result'>No results found <i class='fa fa-spinner fa-pulse'></i></p>
        


        
            <div id="switch-btn" class="switch-btn">
                <div class="icon">
                    <div class="icon-ctn">
                        <div class="icon-wrap icon-house" data-idx="0">
                            <div class="birdhouse"></div>
                            <div class="birdhouse_holes"></div>
                        </div>
                        <div class="icon-wrap icon-ribbon hide" data-idx="1">
                            <div class="ribbon"></div>
                        </div>
                        
                        <div class="icon-wrap icon-link hide" data-idx="2">
                            <div class="loopback_l"></div>
                            <div class="loopback_r"></div>
                        </div>
                        
                        
                        <div class="icon-wrap icon-me hide" data-idx="3">
                            <div class="user"></div>
                            <div class="shoulder"></div>
                        </div>
                        
                    </div>
                    
                </div>
                <div class="tips-box hide">
                    <div class="tips-arrow"></div>
                    <ul class="tips-inner">
                        <li>菜单</li>
                        <li>标签</li>
                        
                        <li>友情链接</li>
                        
                        
                        <li>关于我</li>
                        
                    </ul>
                </div>
            </div>
        

        <div id="switch-area" class="switch-area">
            <div class="switch-wrap">
                <section class="switch-part switch-part1">
                    <nav class="header-menu">
                        <ul>
                        
                            <li><a href="/">主页</a></li>
                        
                            <li><a href="/archives/">所有文章</a></li>
                        
                            <li><a href="/tags/">标签云</a></li>
                        
                            <li><a href="/about/">关于我</a></li>
                        
                        </ul>
                    </nav>
                    <nav class="header-nav">
                        <ul class="social">
                            
                                <a class="fa Email" href="mailto:hatboy-dj@qq.com" title="Email"></a>
                            
                                <a class="fa GitHub" href="https://github.com/HatBoy/" title="GitHub"></a>
                            
                                <a class="fa GitHub博客" href="https://hatboy.github.io/" title="GitHub博客"></a>
                            
                                <a class="fa CSDN" href="http://blog.csdn.net/dj1174232716" title="CSDN"></a>
                            
                        </ul>
                    </nav>
                </section>
                
                
                <section class="switch-part switch-part2">
                    <div class="widget tagcloud" id="js-tagcloud">
                        <ul class="tag-list"><li class="tag-list-item"><a class="tag-list-link" href="/tags/Cython/">Cython</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/Python/">Python</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/Python-tips/">Python tips</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/Python模块tips/">Python模块tips</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/Python语法/">Python语法</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/asyncio/">asyncio</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/异步并发/">异步并发</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/调试/">调试</a></li></ul>
                    </div>
                </section>
                
                
                
                <section class="switch-part switch-part3">
                    <div id="js-friends">
                    
                      <a class="main-nav-link switch-friends-link" href="http://fmxfmx.gitee.io/">FMX</a>
                    
                      <a class="main-nav-link switch-friends-link" href="http://jewelz.me/">Jewelz</a>
                    
                      <a class="main-nav-link switch-friends-link" href="https://www.zhihu.com/people/talentisan/activities">轻狂书生</a>
                    
                      <a class="main-nav-link switch-friends-link" href="http://threetop.top/">ZCC</a>
                    
                      <a class="main-nav-link switch-friends-link" href="http://blog.csdn.net/u012017783">ZCC的CSDN</a>
                    
                      <a class="main-nav-link switch-friends-link" href="http://zcc888.gitee.io/">ZCC的博客</a>
                    
                    </div>
                </section>
                

                
                
                <section class="switch-part switch-part4">
                
                    <div id="js-aboutme">一枚爱Python,爱海贼,爱健身,喜欢好玩有趣事物的程序员……</div>
                </section>
                
            </div>
        </div>
    </header>                
</div>
    </div>
    <div class="mid-col">
      <nav id="mobile-nav">
      <div class="overlay">
          <div class="slider-trigger"></div>
          <h1 class="header-author js-mobile-header hide"><a href="/" title="回到主页">HatBoy</a></h1>
      </div>
    <div class="intrude-less">
        <header id="header" class="inner">
            <a href="/" class="profilepic">
                <img src="/img/avatar.jpg" class="animated zoomIn">
            </a>
            <hgroup>
              <h1 class="header-author"><a href="/" title="回到主页">HatBoy</a></h1>
            </hgroup>
            
            <nav class="header-menu">
                <ul>
                
                    <li><a href="/">主页</a></li>
                
                    <li><a href="/archives/">所有文章</a></li>
                
                    <li><a href="/tags/">标签云</a></li>
                
                    <li><a href="/about/">关于我</a></li>
                
                <div class="clearfix"></div>
                </ul>
            </nav>
            <nav class="header-nav">
                        <ul class="social">
                            
                                <a class="fa Email" target="_blank" href="mailto:hatboy-dj@qq.com" title="Email"></a>
                            
                                <a class="fa GitHub" target="_blank" href="https://github.com/HatBoy/" title="GitHub"></a>
                            
                                <a class="fa GitHub博客" target="_blank" href="https://hatboy.github.io/" title="GitHub博客"></a>
                            
                                <a class="fa CSDN" target="_blank" href="http://blog.csdn.net/dj1174232716" title="CSDN"></a>
                            
                        </ul>
            </nav>
        </header>                
    </div>
    <link class="menu-list" tags="标签" friends="友情链接" about="关于我"/>
</nav>
      <div class="body-wrap"><article id="post-第五章-Cython和扩展类型" class="article article-type-post" itemscope itemprop="blogPost">
  
    <div class="article-meta">
      <a href="/2017/08/10/第五章-Cython和扩展类型/" class="article-date">
      <time datetime="2017-08-10T09:08:07.000Z" itemprop="datePublished">2017-08-10</time>
</a>


    </div>
  
  <div class="article-inner">
    
      <input type="hidden" class="isFancy" />
    
    
      <header class="article-header">
        
  
    <h1 class="article-title" itemprop="name">
      第五章 Cython和扩展类型
    </h1>
  

      </header>
      
      <div class="article-info article-info-post">
        

        
    <div class="article-tag tagcloud">
        <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/Cython/">Cython</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/Python/">Python</a></li></ul>
    </div>

        <div class="clearfix"></div>
      </div>
      
    
    <div class="article-entry" itemprop="articleBody">
      
          
        <excerpt in="" index="" |="" 首页摘要="">

<p>前面几章介绍了Cython如何和Python一起工作，侧重于基础数据类型和函数，Cython也能在Python类上面做一样好，本章我们将继续学习。</p>
<a id="more"></a>
<the rest="" of="" contents="" |="" 余下全文="">

<h2 id="比较Python类和扩展类型"><a href="#比较Python类和扩展类型" class="headerlink" title="比较Python类和扩展类型"></a>比较Python类和扩展类型</h2><p>Python中一切皆为对象，对象有三个基本元素：id、value和type。对象的类型指定了该对象的行为，他们的行为通过特殊的方法控制。Python允许我们创建新的类型，也就是类，通过class关键字定义，本章我们将看到Cython如何允许底层的C访问对象的数据和方法，和他带来的好处。<br>我们可以使用Python/C API来用C语言直接创建扩展类型，效率会显著提升，但是要熟悉Python/C API，编写难度大，这个时候就有了Cython的用武之地了：Cython创建和使用扩展类型和纯Python的一样简单，Cython使用cdef class代码块，和纯Python类有很多相同的地方。</p>
<h2 id="Cython中的扩展类型"><a href="#Cython中的扩展类型" class="headerlink" title="Cython中的扩展类型"></a>Cython中的扩展类型</h2><p>举个例子，有下面一个类：<br><figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line"><span class="class"><span class="keyword">class</span> <span class="title">Particle</span><span class="params">(object)</span>:</span></div><div class="line">    <span class="string">"""Simple Particle type."""</span></div><div class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self, m, p, v)</span>:</span></div><div class="line">        self.mass = m</div><div class="line">        self.position = p</div><div class="line">        self.velocity = v</div><div class="line">    <span class="function"><span class="keyword">def</span> <span class="title">get_momentum</span><span class="params">(self)</span>:</span></div><div class="line">        <span class="keyword">return</span> self.mass * self.velocity</div></pre></td></tr></table></figure></p>
<p>上面是一个纯Python类，我们可以使用Cython编译这个类为C语言，生成的代码使用了Python/C API，和纯Python编写基本上没区别，因为绕过了解释器，所以性能可能得到一点点提升，但是没有从静态类型中得到任何好处。<br>将上面的类转化为Cython的扩展类型如下：<br><figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div></pre></td><td class="code"><pre><div class="line">cdef <span class="class"><span class="keyword">class</span> <span class="title">Particle</span>:</span></div><div class="line">    <span class="string">"""Simple Particle extension type."""</span></div><div class="line">    cdef double mass, position, velocity</div><div class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self, m, p, v)</span>:</span></div><div class="line">        self.mass = m</div><div class="line">        self.position = p</div><div class="line">        self.velocity = v</div><div class="line">    <span class="function"><span class="keyword">def</span> <span class="title">get_momentum</span><span class="params">(self)</span>:</span></div><div class="line">        <span class="keyword">return</span> self.mass * self.velocity</div></pre></td></tr></table></figure></p>
<p>cdef class声明告诉Cython生成一个扩展类型而不是一个Python类，C级别的实例属性和C++或者Java类似，所以所有的属性必须定义，否则初始化调用<strong>init</strong>()函数会抛出属性未定义异常。<br>编译使用我们的例子：<br><figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div></pre></td><td class="code"><pre><div class="line">In [<span class="number">1</span>]: <span class="keyword">import</span> pyximport; pyximport.install()</div><div class="line">Out[<span class="number">1</span>]: (<span class="keyword">None</span>, &lt;pyximport.pyximport.PyxImporter at <span class="number">0x101c64290</span>&gt;)</div><div class="line">In [<span class="number">2</span>]: <span class="keyword">import</span> cython_particle</div><div class="line">In [<span class="number">3</span>]: <span class="keyword">import</span> python_particle</div><div class="line">In [<span class="number">6</span>]: py_particle = python_particle.Particle(<span class="number">1.0</span>, <span class="number">2.0</span>, <span class="number">3.0</span>)</div><div class="line">In [<span class="number">7</span>]: cy_particle = cython_particle.Particle(<span class="number">1.0</span>, <span class="number">2.0</span>, <span class="number">3.0</span>)</div><div class="line">In [<span class="number">8</span>]: py_particle.get_momentum()</div><div class="line">Out[<span class="number">8</span>]: <span class="number">3.0</span></div><div class="line">In [<span class="number">9</span>]: cy_particle.get_momentum()</div><div class="line">Out[<span class="number">9</span>]: <span class="number">3.0</span></div><div class="line">In [<span class="number">10</span>]: py_particle.mass, py_particle.position, py_particle.velocity</div><div class="line">Out[<span class="number">10</span>]: (<span class="number">1.0</span>, <span class="number">2.0</span>, <span class="number">3.0</span>)</div><div class="line">In [<span class="number">11</span>]: cy_particle.mass, cy_particle.position, cy_particle.velocity</div><div class="line">Traceback (most recent call last)</div><div class="line">[...]</div><div class="line">AttributeError: <span class="string">'cython_particle.Particle'</span> object has no attribute <span class="string">'mass'</span></div><div class="line">In [<span class="number">13</span>]: py_particle.charge = <span class="number">12.0</span></div><div class="line">In [<span class="number">14</span>]: cy_particle.charge = <span class="number">12.0</span></div><div class="line">Traceback (most recent call last)</div><div class="line">[...]</div><div class="line">AttributeError: <span class="string">'cython_particle.Particle'</span> object has no attribute <span class="string">'charge'</span></div></pre></td></tr></table></figure></p>
<p>从上述例子中我们发现，为什么扩展类型中的实例属性不能从Python中访问？为什么我们不能给扩展类型添加新的属性？因为Cython定义的扩展属性编译的时候实际上是一个C语言结构体，编译的时候已经固定了大小，不能添加和更改新的属性。</p>
<h2 id="类型属性和访问控制"><a href="#类型属性和访问控制" class="headerlink" title="类型属性和访问控制"></a>类型属性和访问控制</h2><p>纯Python类访问属性是通过在<strong>dict</strong>字典中查找，可以任意访问、添加、修改属性，但是性能不高，Cython通过cdef class定义的扩展类型，直接将代码编译为C语言的结构体，性能能得到显著提升，默认情况下扩展类型属性是私有的，但是如何访问Cython的扩展类型的属性了？可以明确的通过Cython设置属性的只读、可写和可读。<br>下面是可读实例：<br><figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div></pre></td><td class="code"><pre><div class="line"><span class="comment">#mass, position, velocity三个属性均只读</span></div><div class="line">cdef <span class="class"><span class="keyword">class</span> <span class="title">Particle</span>:</span></div><div class="line">    <span class="string">"""Simple Particle extension type."""</span></div><div class="line">    cdef readonly double mass, position, velocity</div><div class="line">    <span class="comment">#...</span></div><div class="line"></div><div class="line"><span class="comment">#mass可读，position和velocity对Python不可读</span></div><div class="line">cdef <span class="class"><span class="keyword">class</span> <span class="title">Particle</span>:</span></div><div class="line">    <span class="string">"""Simple Particle extension type."""</span></div><div class="line">    cdef readonly double mass</div><div class="line">    cdef double position, velocity</div><div class="line">    <span class="comment"># ...</span></div><div class="line"></div><div class="line"><span class="comment">#mass属性可读写，position属性只读，velocity属性不可读</span></div><div class="line">cdef <span class="class"><span class="keyword">class</span> <span class="title">Particle</span>:</span></div><div class="line">    <span class="string">"""Simple Particle extension type."""</span></div><div class="line">    cdef public double mass</div><div class="line">    cdef readonly double position</div><div class="line">    cdef double velocity</div><div class="line">    <span class="comment"># ...</span></div></pre></td></tr></table></figure></p>
<h2 id="C层面的初始化和终止"><a href="#C层面的初始化和终止" class="headerlink" title="C层面的初始化和终止"></a>C层面的初始化和终止</h2><p>和Python类的初始化不一样，C层面的扩展类型是本质上是结构体，在调用<strong>init</strong>之前，实例的结构必须分配，所有的字段必须是有效状态，等待初始值。Cython添加了一个特殊的方法<strong>cinit</strong>，其职责是C级别的分配和初始化。在上面的例子中，Particle是可以使用<strong>init</strong>进行初始化的，因为属性都是double类型，但是这取决于扩展类型被继承或者有其他的构造函数，<strong>init</strong>在创建对象中会被调用多次，但是有方法绕过<strong>init</strong>函数，Cython可以确保<strong>cinit</strong>只被调用一次，而且在<strong>init</strong>、<strong>new</strong>或者其他函数之前被调用，Cython通过<strong>cinit</strong>初始化任何参数。如下面例子：<br><figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">from</span> libc.stdlib cimport *</div><div class="line"></div><div class="line">cdef <span class="class"><span class="keyword">class</span> <span class="title">Matrix</span>:</span></div><div class="line">    cdef:</div><div class="line">        unsigned int nrows, ncols</div><div class="line">        double *_matrix</div><div class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__cinit__</span><span class="params">(self, nr, nc)</span>:</span></div><div class="line">        self.nrows = nr</div><div class="line">        self.ncols = nc</div><div class="line">        self._matrix = &lt;double*&gt;malloc(nr * nc * sizeof(double))</div><div class="line">        <span class="keyword">if</span> self._matrix == NULL:</div><div class="line">            <span class="keyword">raise</span> MemoryError()</div><div class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__dealloc__</span><span class="params">(self)</span>:</span></div><div class="line">        <span class="keyword">if</span> self._matrix != NULL:</div><div class="line">            free(self._matrix)</div></pre></td></tr></table></figure></p>
<p>上面的例子中如果self._matrix放在<strong>init</strong>中初始化，那个<strong>init</strong>永远不会被调用，使用self._matrix就会失败，如果<strong>init</strong>调用多次，会造成内存泄露。<br>Cython通过<strong>dealloc</strong>特殊函数进行清理，释放资源，Cython确保在终止时只调用一次<strong>dealloc</strong>函数来释放<strong>cinit</strong>创建时申请的资源。</p>
<h2 id="cdef和cpdef方法"><a href="#cdef和cpdef方法" class="headerlink" title="cdef和cpdef方法"></a>cdef和cpdef方法</h2><p>在cdef class中我们也可以使用cdef和cpdef方法，但是在普通的Python类中使用会报错。<br>cdef方法和cdef函数类似：所有的参数都是传进去的，所以没有Python到C的类型映射，这也意味着cdef方法只能被Cython代码调用，不能被Python代码调用。<br>cpdef方法和cpdef函数类似：cpdef可以被扩展的Python代码和其他的Cython代码调用，当然，参数值和返回值必须自动的转换为Python对象，所以限制了允许的数据类型，如指针就不行。<br>如下面例子：<br><figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div></pre></td><td class="code"><pre><div class="line">cdef <span class="class"><span class="keyword">class</span> <span class="title">Particle</span>:</span></div><div class="line">    <span class="string">"""Simple Particle extension type."""</span></div><div class="line">    cdef double mass, position, velocity</div><div class="line">    <span class="comment"># ...</span></div><div class="line">    cpdef double get_momentum(self):</div><div class="line">        <span class="keyword">return</span> self.mass * self.velocity</div><div class="line"></div><div class="line"><span class="comment">#我们可以在Python shell或者Python代码中或者Cython代码中运行下面例子</span></div><div class="line"><span class="function"><span class="keyword">def</span> <span class="title">add_momentums</span><span class="params">(particles)</span>:</span></div><div class="line">    <span class="string">"""Returns the sum of the particle momentums."""</span></div><div class="line">    total_mom = <span class="number">0.0</span></div><div class="line">    <span class="keyword">for</span> particle <span class="keyword">in</span> particles:</div><div class="line">        total_mom += particle.get_momentum()</div><div class="line">    <span class="keyword">return</span> total_mom</div></pre></td></tr></table></figure></p>
<p>上面的例子可以看做是Python代码对扩展类的包装，Particle底层的结构和Python对象之间的封装和解包都是自动完成的。我们也可以添加类型信息，这样Cython代码将会生成更快的代码，如下：<br><figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">def</span> <span class="title">add_momentums_typed</span><span class="params">(list particles)</span>:</span></div><div class="line">    <span class="string">"""Returns the sum of the particle momentums."""</span></div><div class="line">    cdef:</div><div class="line">        double total_mom = <span class="number">0.0</span></div><div class="line">        Particle particle</div><div class="line">    <span class="keyword">for</span> particle <span class="keyword">in</span> particles:</div><div class="line">        total_mom += particle.get_momentum()</div><div class="line">    <span class="keyword">return</span> total_mom</div></pre></td></tr></table></figure></p>
<p>上面例子中，如果我们调用particle时不声明类型，性能甚至比纯Python代码还要差。<br>还有一个例子需要比较，如果我们将get_momentum()换成cdef函数其他的不变会怎样？<br><figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line">cdef <span class="class"><span class="keyword">class</span> <span class="title">Particle</span>:</span></div><div class="line">    <span class="string">"""Simple Particle extension type."""</span></div><div class="line">    cdef double mass, position, velocity</div><div class="line">    <span class="comment"># ...</span></div><div class="line">    cpdef double get_momentum(self):</div><div class="line">        <span class="keyword">return</span> self.mass * self.velocity</div><div class="line">    cdef double get_momentum_c(self):</div><div class="line">        <span class="keyword">return</span> self.mass * self.velocity</div></pre></td></tr></table></figure></p>
<p>这个版本性能是最好的，但是get_momentum_c()方法不能被Python调用，只能被Cython调用。</p>
<h2 id="继承和子类"><a href="#继承和子类" class="headerlink" title="继承和子类"></a>继承和子类</h2><p>一个扩展类型可以继承一个基类，但是这个基类必须是用C实现或者内置类型或者其他的扩展类型，常规的Python类或者扩展类型尝试多继承都会报错。<br>例子如下：<br><figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line">cdef <span class="class"><span class="keyword">class</span> <span class="title">CParticle</span><span class="params">(Particle)</span>:</span></div><div class="line">    cdef double momentum</div><div class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self, m, p, v)</span>:</span></div><div class="line">        super(CParticle, self).__init__(m, p, v)</div><div class="line">        self.momentum = self.mass * self.velocity</div><div class="line">    cpdef double get_momentum(self):</div><div class="line">        <span class="keyword">return</span> self.momentum</div></pre></td></tr></table></figure></p>
<p>当然也可以在纯Python中继承Particle类，如下：<br><figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line"><span class="class"><span class="keyword">class</span> <span class="title">PyParticle</span><span class="params">(Particle)</span>:</span></div><div class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self, m, p, v)</span>:</span></div><div class="line">        super(PyParticle, self).__init__(m, p, v)</div><div class="line">    <span class="function"><span class="keyword">def</span> <span class="title">get_momentum</span><span class="params">(self)</span>:</span></div><div class="line">        <span class="keyword">return</span> super(PyParticle, self).get_momentum()</div></pre></td></tr></table></figure></p>
<p>但是PyParticle不能访问Particle中私有的C级别的属性和cdef方法，只能重写def和cpdef方法。不过这样做很慢，穿越Cython/Python边界需要一定的开销。</p>
<h2 id="铸造和子类"><a href="#铸造和子类" class="headerlink" title="铸造和子类"></a>铸造和子类</h2><p>当时用动态类型时，Cython不能访问C级别的数据和方法，所有的属性访问都必须通过Python/C API，这样很慢，但是Cython可以通过定义静态类型或者使用cpdef方法来访问属性而不用通过Python/C API。我们还可以将动态类型赋值给静态类型，如下：<br><figure class="highlight"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div></pre></td><td class="code"><pre><div class="line">cdef Particle static_p = p</div><div class="line">print(static_p.get_momentum())</div><div class="line">print(static_p.velocity)</div><div class="line"><span class="comment">#或者这样使用</span></div><div class="line">print( (&lt;Particle&gt;p).get_momentum())</div><div class="line">print( (&lt;Particle&gt;p).velocity)</div><div class="line"><span class="comment">#下面的方法更加安全</span></div><div class="line">print( (&lt;Particle?&gt;p).get_momentum())</div><div class="line">print( (&lt;Particle?&gt;p).velocity)</div></pre></td></tr></table></figure></p>
<p>如果p不是Particle实例或者他的子类会抛出TypeError异常。</p>
<h2 id="扩展类型对象和None"><a href="#扩展类型对象和None" class="headerlink" title="扩展类型对象和None"></a>扩展类型对象和None</h2><p>有下面一个简单的函数：<br><figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">def</span> <span class="title">dispatch</span><span class="params">(Particle p)</span>:</span></div><div class="line">    <span class="keyword">print</span> p.get_momentum()</div><div class="line">    <span class="keyword">print</span> p.velocity</div><div class="line"></div><div class="line"><span class="comment">#有下面几种使用方式</span></div><div class="line">dispatch(Particle(<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>)) <span class="comment"># OK</span></div><div class="line">dispatch(CParticle(<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>)) <span class="comment"># OK</span></div><div class="line">dispatch(PyParticle(<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>)) <span class="comment"># OK</span></div><div class="line">dispatch(object()) <span class="comment"># TypeError</span></div><div class="line">dispatch(<span class="keyword">None</span>) <span class="comment"># Segmentation fault!</span></div></pre></td></tr></table></figure></p>
<p>Python的None相当于C语言的null，但是本质上None没有C接口，所以尝试用None来访问属性或者方法是无效的，所以dispatch应该先检查p对象是否是None，如下：<br><figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">def</span> <span class="title">dispatch</span><span class="params">(Particle p)</span>:</span></div><div class="line">    <span class="keyword">if</span> p <span class="keyword">is</span> <span class="keyword">None</span>:</div><div class="line">        <span class="keyword">raise</span> TypeError(<span class="string">"..."</span>)</div><div class="line">    <span class="keyword">print</span> p.get_momentum()</div><div class="line">    <span class="keyword">print</span> p.velocity</div><div class="line"></div><div class="line"><span class="comment">#这是一个常见的操作，Cython提供了特殊的语法</span></div><div class="line"><span class="function"><span class="keyword">def</span> <span class="title">dispatch</span><span class="params">(Particle p not None)</span>:</span></div><div class="line">    <span class="keyword">print</span> p.get_momentum()</div><div class="line">    <span class="keyword">print</span> p.velocity</div></pre></td></tr></table></figure></p>
<p>Cython提供了nonecheck编译指令，默认情况下，为了性能，所有函数的的调用都是不安全的，可以通过nonecheck编译指令打开None检查。<br><figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line"><span class="comment">#代码开头添加下面指令</span></div><div class="line"><span class="comment"># cython: nonecheck=True</span></div><div class="line"></div><div class="line"><span class="comment">#或者编译的时候指定</span></div><div class="line">$ cython --directive nonecheck=<span class="keyword">True</span> source.pyx</div></pre></td></tr></table></figure></p>
<h2 id="Cython中的扩展类型属性"><a href="#Cython中的扩展类型属性" class="headerlink" title="Cython中的扩展类型属性"></a>Cython中的扩展类型属性</h2><p>Python的属性访问灵活且功能强大，我们可以在Python类中设置setter和getter方法来方便访问属性，如下：<br><figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line"><span class="class"><span class="keyword">class</span> <span class="title">Particle</span><span class="params">(object)</span>:</span></div><div class="line">    <span class="comment"># ...</span></div><div class="line">    <span class="function"><span class="keyword">def</span> <span class="title">_get_momentum</span><span class="params">(self)</span>:</span></div><div class="line">        <span class="keyword">return</span> self.mass * self.velocity</div><div class="line">    momentum = property(_get_momentum)</div></pre></td></tr></table></figure></p>
<p>Cython针对扩展类型用不同的语法达到了相同的效果：<br><figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div></pre></td><td class="code"><pre><div class="line">cdef <span class="class"><span class="keyword">class</span> <span class="title">Particle</span>:</span></div><div class="line">    <span class="string">"""Simple Particle extension type."""</span></div><div class="line">    cdef double mass, position, velocity</div><div class="line">    <span class="comment"># ...</span></div><div class="line">    property momentum:</div><div class="line">        <span class="string">"""The momentum Particle property."""</span></div><div class="line">        <span class="function"><span class="keyword">def</span> <span class="title">__get__</span><span class="params">(self)</span>:</span></div><div class="line">            <span class="string">"""momentum's getter"""</span></div><div class="line">            <span class="keyword">return</span> self.mass * self.velocity</div><div class="line">        <span class="function"><span class="keyword">def</span> <span class="title">__set__</span><span class="params">(self, m)</span>:</span></div><div class="line">            <span class="string">"""momentum's setter"""</span></div><div class="line">            self.velocity = m / self.mass</div></pre></td></tr></table></figure></p>
<p>我们可以像访问纯Python一样访问Cython属性，如下：<br><figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line">In [<span class="number">3</span>]: p = cython_particle.Particle(<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>)</div><div class="line">In [<span class="number">4</span>]: p.momentum</div><div class="line">Out[<span class="number">4</span>]: <span class="number">3.0</span></div><div class="line">In [<span class="number">5</span>]: p.momentum = <span class="number">4.0</span></div><div class="line">In [<span class="number">6</span>]: p.momentum</div><div class="line">Out[<span class="number">6</span>]: <span class="number">4.0</span></div></pre></td></tr></table></figure></p>
<p>我们可以在Cython中定义相应的<strong>get</strong>、<strong>set</strong>和<strong>del</strong>特殊方法来访问属性，如果哪一个方法没实现就不能访问相应的操作。</p>
<h2 id="特殊方法甚至是更加特别"><a href="#特殊方法甚至是更加特别" class="headerlink" title="特殊方法甚至是更加特别"></a>特殊方法甚至是更加特别</h2><p>当Cython扩展类提供支持操作符重载是，我们必须定义一些特殊方法。前面我们已经讲到了<strong>cinit</strong>、<strong>init</strong>、<strong>dealloc</strong>特殊方法，看到了如何处理C级别的初始化，Python级别的初始化和终止。扩展类型不支持<strong>del</strong>特殊方法，<strong>dealloc</strong>替代了他的功能。</p>
<h3 id="算数方法"><a href="#算数方法" class="headerlink" title="算数方法"></a>算数方法</h3><p>在纯Python中，为了完全重载+操作符号，需要重写<strong>add</strong>和<strong>radd</strong>特殊方法，但是Cython只需要重载<strong>add</strong>就够了，他实现了<strong>add</strong>和<strong>radd</strong>的功能。下面有一个简单的例子：<br><figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div></pre></td><td class="code"><pre><div class="line">cdef <span class="class"><span class="keyword">class</span> <span class="title">E</span>:</span></div><div class="line">    <span class="string">"""Extension type that supports addition."""</span></div><div class="line">    cdef int data</div><div class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self, d)</span>:</span></div><div class="line">        self.data = d</div><div class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__add__</span><span class="params">(x, y)</span>:</span></div><div class="line">        <span class="comment"># Regular __add__ behavior</span></div><div class="line">        <span class="keyword">if</span> isinstance(x, E):</div><div class="line">            <span class="keyword">if</span> isinstance(y, int):</div><div class="line">                <span class="keyword">return</span> (&lt;E&gt;x).data + y</div><div class="line">        <span class="comment"># __radd__ behavior</span></div><div class="line">        <span class="keyword">elif</span> isinstance(y, E):</div><div class="line">            <span class="keyword">if</span> isinstance(x, int):</div><div class="line">                <span class="keyword">return</span> (&lt;E&gt;y).data + x</div><div class="line">        <span class="keyword">else</span>:</div><div class="line">             <span class="keyword">return</span> <span class="built_in">NotImplemented</span></div></pre></td></tr></table></figure></p>
<p>Cython不会自动的转换传入<strong>add</strong>中的参数类型，需要检查实例，确保能成功访问每一个E实例对象的data属性。</p>
<h3 id="丰富的比较操作符"><a href="#丰富的比较操作符" class="headerlink" title="丰富的比较操作符"></a>丰富的比较操作符</h3><p>Cython扩展类型不支持比较操作的特殊方法，如<strong>eq</strong>、<strong>lt</strong>和<strong>le</strong>等特殊方法。但是Cython提供了一个单独的特殊方法<strong>richcmp</strong>(x, y, op)，通过第三个参数来执行要比较的操作。对应关系如下：<br><img src="/2017/08/10/第五章-Cython和扩展类型/1.png" alt="对应关系"></p>
<p> 表中整数参数是编译时定义在object.h中的常量，我们可以导入这些常量。如下面例子：<br><figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">from</span> cpython.object cimport Py_LT, Py_LE, Py_EQ, Py_GE, Py_GT, Py_NE</div><div class="line"></div><div class="line">cdef <span class="class"><span class="keyword">class</span> <span class="title">R</span>:</span></div><div class="line">    <span class="string">"""Extension type that supports rich comparisons."""</span></div><div class="line">    cdef double data</div><div class="line">        <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self, d)</span>:</span></div><div class="line">            self.data = d</div><div class="line">        <span class="function"><span class="keyword">def</span> <span class="title">__richcmp__</span><span class="params">(x, y, int op)</span>:</span></div><div class="line">            cdef:</div><div class="line">                R r</div><div class="line">                double data</div><div class="line">            <span class="comment"># Make r always refer to the R instance.</span></div><div class="line">            r, y = (x, y) <span class="keyword">if</span> isinstance(x, R) <span class="keyword">else</span> (y, x)</div><div class="line">            data = r.data</div><div class="line">            <span class="keyword">if</span> op == Py_LT:</div><div class="line">                <span class="keyword">return</span> data &lt; y</div><div class="line">            <span class="keyword">elif</span> op == Py_LE:</div><div class="line">                <span class="keyword">return</span> data &lt;= y</div><div class="line">            <span class="keyword">elif</span> op == Py_EQ:</div><div class="line">                <span class="keyword">return</span> data == y</div><div class="line">            <span class="keyword">elif</span> op == Py_NE:</div><div class="line">                <span class="keyword">return</span> data != y</div><div class="line">            <span class="keyword">elif</span> op == Py_GT:</div><div class="line">                <span class="keyword">return</span> data &gt; y</div><div class="line">            <span class="keyword">elif</span> op == Py_GE:</div><div class="line">                <span class="keyword">return</span> data &gt;= y</div><div class="line">            <span class="keyword">else</span>:</div><div class="line">                <span class="keyword">assert</span> <span class="keyword">False</span></div></pre></td></tr></table></figure></p>
<p>效果如下：<br><figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div></pre></td><td class="code"><pre><div class="line">In [<span class="number">1</span>]: <span class="keyword">import</span> pyximport; pyximport.install()</div><div class="line">Out[<span class="number">1</span>]: (<span class="keyword">None</span>, &lt;pyximport.pyximport.PyxImporter at <span class="number">0x101c7d290</span>&gt;)</div><div class="line">In [<span class="number">2</span>]: <span class="keyword">from</span> special_methods <span class="keyword">import</span> R</div><div class="line">In [<span class="number">3</span>]: r = R(<span class="number">10</span>)</div><div class="line">In [<span class="number">4</span>]: r &lt; <span class="number">20</span> <span class="keyword">and</span> <span class="number">20</span> &gt; r</div><div class="line">Out[<span class="number">4</span>]: <span class="keyword">True</span></div><div class="line">In [<span class="number">5</span>]: r &gt; <span class="number">20</span> <span class="keyword">and</span> <span class="number">20</span> &lt; r</div><div class="line">Out[<span class="number">5</span>]: <span class="keyword">False</span></div><div class="line">In [<span class="number">6</span>]: <span class="number">0</span> &lt;= r &lt;= <span class="number">100</span></div><div class="line">Out[<span class="number">6</span>]: <span class="keyword">True</span></div><div class="line">In [<span class="number">7</span>]: r == <span class="number">10</span></div><div class="line">Out[<span class="number">7</span>]: <span class="keyword">True</span></div><div class="line">In [<span class="number">8</span>]: r != <span class="number">10</span></div><div class="line">Out[<span class="number">8</span>]: <span class="keyword">False</span></div><div class="line">In [<span class="number">9</span>]: r == <span class="number">20</span></div><div class="line">Out[<span class="number">9</span>]: <span class="keyword">False</span></div><div class="line">In [<span class="number">10</span>]: <span class="number">20</span> == r</div><div class="line">Out[<span class="number">10</span>]: <span class="keyword">False</span></div></pre></td></tr></table></figure></p>
<h3 id="迭代器支持"><a href="#迭代器支持" class="headerlink" title="迭代器支持"></a>迭代器支持</h3><p>为了让扩展类型可迭代，我们在里面定义了<strong>iter</strong>，就像在纯Python中使用一样，为了让扩展类型成为迭代器，我们在里面定义了<strong>next</strong>特殊方法。例子如下：<br><figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div></pre></td><td class="code"><pre><div class="line">cdef <span class="class"><span class="keyword">class</span> <span class="title">I</span>:</span></div><div class="line">    cdef:</div><div class="line">        list data</div><div class="line">        int i</div><div class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self)</span>:</span></div><div class="line">        self.data = range(<span class="number">100</span>)</div><div class="line">        self.i = <span class="number">0</span></div><div class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__iter__</span><span class="params">(self)</span>:</span></div><div class="line">        <span class="keyword">return</span> self</div><div class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__next__</span><span class="params">(self)</span>:</span></div><div class="line">        <span class="keyword">if</span> self.i &gt;= len(self.data):</div><div class="line">            <span class="keyword">raise</span> StopIteration()</div><div class="line">        ret = self.data[self.i]</div><div class="line">        self.i += <span class="number">1</span></div><div class="line">        <span class="keyword">return</span> ret</div></pre></td></tr></table></figure></p>
<p>上面的特殊方法只是列举了一部分，更多的特殊方法吗，请参看Cython的官方文档：<a href="http://docs.cython.org/en/latest/" target="_blank" rel="external">http://docs.cython.org/en/latest/</a></p>
</the></excerpt>
      
    </div>
    
  </div>
  
    
    <div class="copyright">
        <p><span>本文标题:</span><a href="/2017/08/10/第五章-Cython和扩展类型/">第五章 Cython和扩展类型</a></p>
        <p><span>文章作者:</span><a href="/" title="回到主页">HatBoy</a></p>
        <p><span>发布时间:</span>2017-08-10, 17:08:07</p>
        <p><span>最后更新:</span>2017-12-21, 18:14:31</p>
        <p>
            <span>原始链接:</span><a class="post-url" href="/2017/08/10/第五章-Cython和扩展类型/" title="第五章 Cython和扩展类型">http://hatboy.gitee.io/2017/08/10/第五章-Cython和扩展类型/</a>
            <span class="copy-path" data-clipboard-text="原文: http://hatboy.gitee.io/2017/08/10/第五章-Cython和扩展类型/　　作者: HatBoy" title="点击复制文章链接"><i class="fa fa-clipboard"></i></span>
            <script> var clipboard = new Clipboard('.copy-path'); </script>
        </p>
        <p>
            <span>许可协议:</span><i class="fa fa-creative-commons"></i> <a rel="license" href="http://creativecommons.org/licenses/by-nc-sa/4.0/" title="CC BY-NC-SA 4.0 International" target = "_blank">"署名-非商用-相同方式共享 4.0"</a> 转载请保留原文链接及作者。
        </p>
    </div>



    <nav id="article-nav">
        
            <div id="article-nav-newer" class="article-nav-title">
                <a href="/2017/08/16/第六章-组织Cython代码/">
                    第六章 组织Cython代码
                </a>
            </div>
        
        
            <div id="article-nav-older" class="article-nav-title">
                <a href="/2017/07/31/第四章-Cython实践：N-body模拟/">
                    第四章 Cython实践：N-body模拟
                </a>
            </div>
        
    </nav>

  
</article>

    <div id="toc" class="toc-article">
        <strong class="toc-title">文章目录</strong>
        
            <ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#比较Python类和扩展类型"><span class="toc-number">1.</span> <span class="toc-text">比较Python类和扩展类型</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Cython中的扩展类型"><span class="toc-number">2.</span> <span class="toc-text">Cython中的扩展类型</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#类型属性和访问控制"><span class="toc-number">3.</span> <span class="toc-text">类型属性和访问控制</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#C层面的初始化和终止"><span class="toc-number">4.</span> <span class="toc-text">C层面的初始化和终止</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#cdef和cpdef方法"><span class="toc-number">5.</span> <span class="toc-text">cdef和cpdef方法</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#继承和子类"><span class="toc-number">6.</span> <span class="toc-text">继承和子类</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#铸造和子类"><span class="toc-number">7.</span> <span class="toc-text">铸造和子类</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#扩展类型对象和None"><span class="toc-number">8.</span> <span class="toc-text">扩展类型对象和None</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Cython中的扩展类型属性"><span class="toc-number">9.</span> <span class="toc-text">Cython中的扩展类型属性</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#特殊方法甚至是更加特别"><span class="toc-number">10.</span> <span class="toc-text">特殊方法甚至是更加特别</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#算数方法"><span class="toc-number">10.1.</span> <span class="toc-text">算数方法</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#丰富的比较操作符"><span class="toc-number">10.2.</span> <span class="toc-text">丰富的比较操作符</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#迭代器支持"><span class="toc-number">10.3.</span> <span class="toc-text">迭代器支持</span></a></li></ol></li></ol>
        
    </div>
    <style>
        .left-col .switch-btn,
        .left-col .switch-area {
            display: none;
        }
        .toc-level-3 i,
        .toc-level-3 ol {
            display: none !important;
        }
    </style>

    <input type="button" id="tocButton" value="隐藏目录"  title="点击按钮隐藏或者显示文章目录">

    <script>
        yiliaConfig.toc = ["隐藏目录", "显示目录", !!"false"];
    </script>



    
<div class="share">
    
        <div class="bdsharebuttonbox">
            <a href="#" class="fa fa-twitter bds_twi" data-cmd="twi" title="分享到推特"></a>
            <a href="#" class="fa fa-weibo bds_tsina" data-cmd="tsina" title="分享到新浪微博"></a>
            <a href="#" class="fa fa-qq bds_sqq" data-cmd="sqq" title="分享给 QQ 好友"></a>
            <a href="#" class="fa fa-files-o bds_copy" data-cmd="copy" title="复制网址"></a>
            <a href="#" class="fa fa fa-envelope-o bds_mail" data-cmd="mail" title="通过邮件分享"></a>
            <a href="#" class="fa fa-weixin bds_weixin" data-cmd="weixin" title="生成文章二维码"></a>
            <a href="#" class="fa fa-share-alt bds_more" data-cmd="more"></i></a>
        </div>
        <script>
            window._bd_share_config={
                "common":{"bdSnsKey":{},"bdText":"第五章 Cython和扩展类型　| HatBoy的个人主页　","bdMini":"2","bdMiniList":false,"bdPic":"","bdStyle":"0","bdSize":"24"},"share":{}};with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='http://bdimg.share.baidu.com/static/api/js/share.js?v=89860593.js?cdnversion='+~(-new Date()/36e5)];
        </script>
    

    
</div>







    




    <div class="scroll" id="post-nav-button">
        
            <a href="/2017/08/16/第六章-组织Cython代码/" title="上一篇: 第六章 组织Cython代码">
                <i class="fa fa-angle-left"></i>
            </a>
        

        <a title="文章列表"><i class="fa fa-bars"></i><i class="fa fa-times"></i></a>

        
            <a href="/2017/07/31/第四章-Cython实践：N-body模拟/" title="下一篇: 第四章 Cython实践：N-body模拟">
                <i class="fa fa-angle-right"></i>
            </a>
        
    </div>

    <ul class="post-list"><li class="post-list-item"><a class="post-list-link" href="/2018/02/27/如何恢复丢失的Python源代码如果它还在内存中运行/">如何恢复丢失的Python源代码如果它还在内存中运行</a></li><li class="post-list-item"><a class="post-list-link" href="/2018/02/08/pathlib：文件系统路径作为对象/">pathlib：文件系统路径作为对象</a></li><li class="post-list-item"><a class="post-list-link" href="/2017/12/21/asyncio：异步IO、事件循环和并发/">asyncio：异步IO、事件循环和并发</a></li><li class="post-list-item"><a class="post-list-link" href="/2017/12/21/asyncio之调试asyncio/">asyncio之调试asyncio</a></li><li class="post-list-item"><a class="post-list-link" href="/2017/12/21/asyncio之协程结合线程和进程/">asyncio之协程结合线程和进程</a></li><li class="post-list-item"><a class="post-list-link" href="/2017/12/21/asyncio之接收Unix信号/">asyncio之接收Unix信号</a></li><li class="post-list-item"><a class="post-list-link" href="/2017/12/21/asyncio之使用子进程/">asyncio之使用子进程</a></li><li class="post-list-item"><a class="post-list-link" href="/2017/12/21/asyncio之与DNS服务进行交互/">asyncio之与DNS服务进行交互</a></li><li class="post-list-item"><a class="post-list-link" href="/2017/12/21/asyncio之使用SSL/">asyncio之使用SSL</a></li><li class="post-list-item"><a class="post-list-link" href="/2017/12/21/asyncio之使用协程和流的异步I-O/">asyncio之使用协程和流的异步I/O</a></li><li class="post-list-item"><a class="post-list-link" href="/2017/12/21/asyncio之协议抽象类的异步I-O/">asyncio之协议抽象类的异步I/O</a></li><li class="post-list-item"><a class="post-list-link" href="/2017/12/21/asyncio之同步原语/">asyncio之同步原语</a></li><li class="post-list-item"><a class="post-list-link" href="/2017/12/21/asyncio之用控制结构组建协程/">asyncio之用控制结构组建协程</a></li><li class="post-list-item"><a class="post-list-link" href="/2017/12/21/asyncio之并发执行Tasks/">asyncio之并发执行Tasks</a></li><li class="post-list-item"><a class="post-list-link" href="/2017/12/21/asyncio之异步生产结果/">asyncio之异步生产结果</a></li><li class="post-list-item"><a class="post-list-link" href="/2017/12/21/asyncio之定时调度常规函数/">asyncio之定时调度常规函数</a></li><li class="post-list-item"><a class="post-list-link" href="/2017/12/21/asyncio之使用协程处理多任务/">asyncio之使用协程处理多任务</a></li><li class="post-list-item"><a class="post-list-link" href="/2017/12/21/asyncio之异步并发的概念/">asyncio之异步并发的概念</a></li><li class="post-list-item"><a class="post-list-link" href="/2017/12/21/Python上下文管理器/">Python上下文管理器</a></li><li class="post-list-item"><a class="post-list-link" href="/2017/12/21/Python-importlib讲解/">Python importlib讲解</a></li><li class="post-list-item"><a class="post-list-link" href="/2017/12/21/第七章-用Cython包装C库/">第七章 用Cython包装C库</a></li><li class="post-list-item"><a class="post-list-link" href="/2017/08/16/第六章-组织Cython代码/">第六章 组织Cython代码</a></li><li class="post-list-item"><a class="post-list-link" href="/2017/08/10/第五章-Cython和扩展类型/">第五章 Cython和扩展类型</a></li><li class="post-list-item"><a class="post-list-link" href="/2017/07/31/第四章-Cython实践：N-body模拟/">第四章 Cython实践：N-body模拟</a></li><li class="post-list-item"><a class="post-list-link" href="/2017/07/31/Python性能分析与调试/">Python性能分析与调试</a></li><li class="post-list-item"><a class="post-list-link" href="/2017/07/17/第三章-深入Cython/">第三章 深入Cython</a></li><li class="post-list-item"><a class="post-list-link" href="/2017/07/03/第二章-编译和运行Cython代码/">第二章 编译和运行Cython代码</a></li><li class="post-list-item"><a class="post-list-link" href="/2017/07/02/第一章-Cython简介/">第一章 Cython简介</a></li></ul>




    <script>
        
    </script>
</div>
      <footer id="footer">
    <div class="outer">
        <div id="footer-info">
            <div class="footer-left">
                <i class="fa fa-copyright"></i> 
                2017-2018 HatBoy
            </div>
            <div class="footer-right">
                <a href="http://hexo.io/" target="_blank" title="快速、简洁且高效的博客框架">Hexo</a>  Theme <a href="https://github.com/MOxFIVE/hexo-theme-yelee" target="_blank" title="简而不减 Hexo 双栏博客主题  v3.5">Yelee</a> by MOxFIVE <i class="fa fa-heart animated infinite pulse"></i>
            </div>
        </div>
        
            <div class="visit">
                
                    <span id="busuanzi_container_site_pv" style='display:none'>
                        <span id="site-visit" title="本站到访数"><i class="fa fa-user" aria-hidden="true"></i><span id="busuanzi_value_site_uv"></span>
                        </span>
                    </span>
                
                
                    <span>| </span>
                
                
                    <span id="busuanzi_container_page_pv" style='display:none'>
                        <span id="page-visit"  title="本页阅读量"><i class="fa fa-eye animated infinite pulse" aria-hidden="true"></i><span id="busuanzi_value_page_pv"></span>
                        </span>
                    </span>
                
            </div>
        
    </div>
</footer>
    </div>
    
<script data-main="/js/main.js" src="//cdn.bootcss.com/require.js/2.2.0/require.min.js"></script>





    <script type="text/x-mathjax-config">
MathJax.Hub.Config({
    tex2jax: {
        inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
        processEscapes: true,
        skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
    }
});

MathJax.Hub.Queue(function() {
    var all = MathJax.Hub.getAllJax(), i;
    for(i=0; i < all.length; i += 1) {
        all[i].SourceElement().parentNode.className += ' has-jax';                 
    }       
});
</script>

<script src="//cdn.bootcss.com/mathjax/2.6.1/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
</script>


<div class="scroll" id="scroll">
    <a href="#" title="返回顶部"><i class="fa fa-arrow-up"></i></a>
    <a href="#comments" onclick="load$hide();" title="查看评论"><i class="fa fa-comments-o"></i></a>
    <a href="#footer" title="转到底部"><i class="fa fa-arrow-down"></i></a>
</div>
<script>
    // Open in New Window
    
        $("a").attr("target", "_blank");
        $("#scroll a, #toc a").removeAttr("target");
    
</script>

<script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js">
</script>
  </div>
</body>
</html>